﻿using Sunny.UI;
using System;
using System.IO.Pipes;
using System.IO;
using System.Threading;
using CoreShop.Model;
using CoreShop.Services;
using System.Collections.Generic;
using System.Linq;
using CoreShop.Library;
using CoreShop.Model.FromBody;
using CoreShop.Services.Services.Report;
using CoreShop.App.Units;
using System.Windows.Forms;
using System.Reflection;
using gregn6Lib;

namespace CoreShop.App
{
    public partial class fpgOrderDetail : UIPage
    {
        public int mPageIndex = 0;
        protected GridppReport Report = new GridppReport();
        private PosReportRequest _posReport = new PosReportRequest();
        private List<ReportOrderDetail> lstSource = new List<ReportOrderDetail>();

        public fpgOrderDetail()
        {
            InitializeComponent();
            LoadPara();
        }

        //在C#中一次填入一条记录不能成功，只能使用一次将记录全部填充完的方式
        private void ReportFetchRecord()
        {
            try
            {
                Report.DetailGrid.Recordset.Empty();
                if ((lstSource == null) || (lstSource.Count == 0)) return;
                var taskdetail1 = lstSource.First();
                PropertyInfo[] properties1 = taskdetail1.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);

                foreach (var row in lstSource)
                {
                    Report.DetailGrid.Recordset.Append();
                    #region 商品明细与Grid++Report记录集的字段之间的对应关系
                    foreach (PropertyInfo item1 in properties1)
                    {
                        string name = item1.Name;
                        object value = item1.GetValue(row, null);

                        foreach (IGRField fld in Report.DetailGrid.Recordset.Fields)
                        {
                            if (String.Compare(fld.RunningDBField, name, true) == 0)
                            {
                                fld.Value = value;
                                break;
                            }
                        }
                    }
                    #endregion

                    #region 参数与Grid++Report记录集的字段之间的对应关系
                    if (_posReport != null)
                    {
                        PropertyInfo[] properties2 = _posReport.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                        foreach (PropertyInfo item2 in properties2)
                        {
                            string name = item2.Name;
                            object value = item2.GetValue(_posReport, null);

                            foreach (IGRField fld in Report.DetailGrid.Recordset.Fields)
                            {
                                if ((String.Compare(fld.RunningDBField, name, true) == 0) && (!name.Equals("quantity", StringComparison.OrdinalIgnoreCase)))
                                {
                                    fld.Value = value;
                                    break;
                                }
                            }
                        }
                    }
                    #endregion


                    Report.DetailGrid.Recordset.Post();
                }
            }
            catch (Exception ex) { }
        }

        private void LoadPara()
        {
            this.tab2_foodtype.Items.Clear();
            List<corecmsfoodcategory> foodtypeGrid = new List<corecmsfoodcategory>();
            var foodtype0 = new corecmsfoodcategory();
            foodtype0.id = 0;
            foodtype0.name = "全部";
            List<corecmsfoodcategory> foodtype = new corecmsfoodcategoryServices().GetList().Where(p => p.isDelete == false).ToList();
            foodtypeGrid.Add(foodtype0);
            foodtypeGrid.AddRange(foodtype);
            tab2_foodtype.DataSource = foodtypeGrid;
            tab2_foodtype.DisplayMember = "name";
            tab2_foodtype.ValueMember = "id";
            if (foodtype.Count > 0) this.tab2_foodtype.SelectedIndex = 0;
        }

        private void LoadData(PosReportRequest posReport)
        {
            _posReport = posReport;
            int count = 0;
            lstSource = new corereportServices().Getcorecmsfoodorderdetail(ref count, mPageIndex, pgPageFooter.PageSize, posReport.starTime, posReport.endTime, this.txt2_classNumber.Text, CommFunc.ConvertToInt32(this.tab2_foodtype.SelectedValue), this.txtfoodName.Text);
            pgPageFooter.TotalCount = count;
            this.dgvSaleDetailList.AutoGenerateColumns = false;
            this.dgvSaleDetailList.DataSource = lstSource;
            PageTotal.DataGridView = dgvSaleDetailList;
            PageTotal["classNumber"] = "合计：";
            PageTotal["Column2_quantity"] = CommFunc.ConvertToString(lstSource.Sum(p => p.quantity));
            PageTotal["Column2_price"] = CommFunc.ConvertToString(lstSource.Sum(p => p.price));
            PageTotal["Column2_amount"] = CommFunc.ConvertToString(lstSource.Sum(p => p.amount));
            PageTotal["Column2_taskAmount"] = CommFunc.ConvertToString(lstSource.Sum(p => p.taskAmount));
            PageTotal["Column2_feedAmount"] = CommFunc.ConvertToString(lstSource.Sum(p => p.feedAmount));
            PageTotal["Column2_reduceAmount"] = CommFunc.ConvertToString(lstSource.Sum(p => p.reduceAmount));
            PageTotal["Column2_realAmount"] = CommFunc.ConvertToString(lstSource.Sum(p => p.realAmount));
            PageTotal["Column2_allAmount"] = CommFunc.ConvertToString(lstSource.Sum(p => p.allAmount));
            PageTotal["point"] = CommFunc.ConvertToString(lstSource.Sum(p => p.point));
        }

        private void ExportData()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.Title = "Export Excel File To";
            saveFileDialog.ShowDialog();
            string fileName = saveFileDialog.FileName;
            if (fileName == "") return;
            Dictionary<string, DataGridView> gridViews = new Dictionary<string, DataGridView>();
            gridViews.Add("销售明细", dgvSaleDetailList);
            if (ExportUtil.NPOIExportForDataGridview(gridViews, fileName))
            {
                MessageBox.Show("导出Excel成功！");
            }
        }


        private void fpgOrderDetail_ReceiveParams(object sender, UIPageParamsArgs e)
        {
            mPageIndex = 1;
            var rptRequest = e.Value as PosReportRequest;
            if (rptRequest.type == (int)GlobalEnumVars.ReportRequest.Query)
            {
                LoadData(rptRequest);
            }
            else {
                ExportData();
            }
        }

        private void btnPrintView_Click(object sender, EventArgs e)
        {
            var billtemplates = new corecmsprintbilltemplateServices().AsQueryable().Where(p=>p.name.Equals(this.Text)).ToList();
            if ((billtemplates == null) || (billtemplates.Count == 0))
            {
                string msg = string.Format("报表打印模板<{0}>不存在，请添加。", this.Text);
                UIMessageBox.Show(msg);
                return;
            }
            var billtemplate = billtemplates.FirstOrDefault();
            Report.LoadFromStr(billtemplate.reportData);
            Report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord);
            Report.PrintPreview(true);
        }
    }
}